﻿using FluentFTP;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;

namespace Jinndev {

    // copy "$(TargetPath)" "$(ProjectDir)..\..\client\FighterGame\build"

    class Program {

        public static string Host = null;
        public static int Port = 21;

        public static string Username = null;
        public static string Password = null;

        static void Main(string[] args) {

            JObject config = ReadConfig(args);

            if (config == null) {
                Console.WriteLine("未找到FtpUploader.json");
                return;
            }

            Host = config.Value<string>("host");
            Port = config.Value<int>("port");

            Username = config.Value<string>("username");
            Password = config.Value<string>("password");

            string localPath = config.Value<string>("localPath");
            string remotePath = config.Value<string>("remotePath");

            //string dir = Path.Combine(Directory.GetCurrentDirectory(), "web-mobile");
            if (Directory.Exists(localPath)) {
                UploadDir(localPath, remotePath);
            }
            else if (File.Exists(localPath)) {
                UpdateFile(localPath, remotePath);
            }
            else {
                Console.WriteLine("未找到: " + localPath);
            }

            WaitQuit();
        }

        static JObject ReadConfig(string[] args) {
            foreach (string arg in args) {
                if (arg.EndsWith(".json") && File.Exists(arg)) {
                    string text = File.ReadAllText(arg);
                    return JObject.Parse(text);
                }
            }

            if (File.Exists("FtpUploader.json")) {
                string text = File.ReadAllText("FtpUploader.json");
                return JObject.Parse(text);
            }
            return null;
        }

        static void WaitQuit() {
            Console.WriteLine("任意键退出..");
            Console.Read();
        }

        static void UpdateFile(string file, string remotePath) {
            FtpClient client = new FtpClient(Host, Port, new NetworkCredential(Username, Password));
            Console.WriteLine("连接中..");
            client.Connect();
            Console.WriteLine("已接中");

            Console.WriteLine("正在上传: " + file + " 到 " + remotePath);
            client.UploadFile(file, remotePath, FtpRemoteExists.Overwrite, true, FtpVerify.None, OnProgress);
            client.Disconnect();

            Console.WriteLine();
            Console.WriteLine("上传完成");
        }

        /// <summary>
        /// 上传目录，包含目录本身
        /// </summary>
        static void UploadDir(string dir, string remotePath) {
            FtpClient client = new FtpClient(Host, Port, new NetworkCredential(Username, Password));
            Console.WriteLine("连接中..");
            client.Connect();
            Console.WriteLine("已连接");

            Console.WriteLine("正在上传: " + dir + " 到 " + remotePath);
            client.UploadDirectory(dir, remotePath, FtpFolderSyncMode.Update, FtpRemoteExists.Overwrite, progress: OnProgress);
            client.Disconnect();

            Console.WriteLine();
            Console.WriteLine("上传完成");
        }

        class UploadProgress : IProgress<FtpProgress> {
            public void Report(FtpProgress value) {
                OnProgress(value);
            }
        }

        static void OnProgress(FtpProgress progress) {
            int length = Console.CursorLeft;
            Console.CursorLeft = 0;
            Console.Write(new string(' ', length));
            Console.CursorLeft = 0;
            Console.Write($"ETA: {progress.ETA}, {progress.Progress / 100:P0}, {progress.FileIndex + 1}/{progress.FileCount}");
        }

        ///// <summary>
        ///// 上传目录，包含目录本身
        ///// </summary>
        //static void UploadDir(string dir) {
        //    var files = Directory.GetFiles(dir, "*", SearchOption.AllDirectories);
        //    string dirName = Path.GetFileName(dir);
        //    WebClient client = GetFtpClient();

        //    for (int i = 0; i < files.Length; i++) {
        //        string file = files[i];
        //        string storePath = dirName + "/" + file.Substring(dir.Length + 1);
        //        Console.Write($"上传\t{storePath}...  ");

        //        try {
        //            var uri = GetUploadUri(storePath);
        //            client.UploadFile(uri, "STOR", file);
        //            Console.WriteLine("成功。");
        //        }
        //        catch (Exception e) {
        //            Console.WriteLine("失败: " + e.Message);
        //            WaitQuit();
        //            break;
        //        }
        //    }
        //}

        //static void CreateDir(WebClient client, string dir) {

        //}


        //public static WebClient GetFtpClient() {
        //    var client = new WebClient();
        //    client.Credentials = new NetworkCredential(Username, Password);
        //    return client;
        //}

        //public static FtpWebRequest GetFtpWebRequest(string storePath) {
        //    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(GetUploadUri(storePath));
        //    request.Credentials = new NetworkCredential(Username, Password);
        //    return request;
        //}

        //public static Uri GetUploadUri(string storePath) {
        //    return new Uri(ServerUri + "/" + storePath);
        //}

    }

}
